//
//  UITextField+Limit.m
//  CJTextInputlimit
//
//  Created by Destiny on 2019/1/21.
//  Copyright © 2019 Destiny. All rights reserved.
//

#import "UITextField+Limit.h"
#import <objc/runtime.h>

#define kDNUMBERS     @"0123456789"
#define kDLETTER     @"abcdefghijklmnopqresuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

static NSString * const CJMaxLengthKey = @"CJMaxLengthKey";
static NSString * const CJTextLengthBlockKey = @"CJTextLengthKey";
static NSString * const CJTextFieldTypeKey = @"CJTextFieldTypeKey";
static NSString * const CJIsTextFieldTypeKey = @"CJIsTextFieldTypeKey";

@implementation UITextField (Limit)

- (void)setMaxLength:(NSInteger)maxLength{
    objc_setAssociatedObject(self, &CJMaxLengthKey, @(maxLength), OBJC_ASSOCIATION_ASSIGN);
    
    [self addTarget:self
             action:@selector(textFielCJTextChanged:)
   forControlEvents:UIControlEventEditingChanged];
}
- (NSInteger)maxLength{
    return   [objc_getAssociatedObject(self, &CJMaxLengthKey) integerValue];
}

- (void)setLengthBlock:(TextLengthBlock)lengthBlock{
    objc_setAssociatedObject(self, &CJTextLengthBlockKey, lengthBlock, OBJC_ASSOCIATION_COPY);
    
    [self addTarget:self
             action:@selector(textFielCJTextChanged:)
   forControlEvents:UIControlEventEditingChanged];
}
- (TextLengthBlock)lengthBlock{
    return objc_getAssociatedObject(self, &CJTextLengthBlockKey);
}

- (void)setTextFieldType:(NSInteger)textFieldType{
    objc_setAssociatedObject(self, &CJTextFieldTypeKey,  @(textFieldType), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)textFieldType{
    return [objc_getAssociatedObject(self, &CJTextFieldTypeKey) integerValue];
}

- (void)setIsTextFieldTypeBlock:(IsTextFieldTypeBlock)isTextFieldTypeBlock{
    objc_setAssociatedObject(self, &CJIsTextFieldTypeKey, isTextFieldTypeBlock, OBJC_ASSOCIATION_COPY);
}
- (IsTextFieldTypeBlock)isTextFieldTypeBlock{
    return objc_getAssociatedObject(self, &CJIsTextFieldTypeKey);
}

- (void)lengthLimitBlock:(UITextField *)textField
{
    if (self.lengthBlock) {
        self.lengthBlock(textField.text.length);
    }
}



- (void)textFielCJTextChanged:(UITextField *)textField
{
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
    
//    textField.text =  [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    switch (self.textFieldType) {
        case CJTextFieldStringTypeNone:
        {
//            [self textFieldStringTypeNone:textField];
        }
            break;
        case CJTextFieldStringTypeNumber:
        {
            [self textFieldStringTypeNumber:textField];
        }
            break;
        case CJTextFieldStringTypeLetter:
        {
            [self textFieldStringTypeLetter:textField];
        }
            break;
        case CJTextFieldStringTypeMoneyValue:
        {
            [self textFieldStringTypeMoneyValue:textField];
        }
            break;
        case CJTextFieldStringTypePassword:
        {
            [self textFieldStringTypePassword:textField];
        }
            break;
        case CJTextFieldStringTypeThreeDecimalPlaces:
        {
            [self textFieldStringTypeThreeDecimalPlaces:textField];
        }
            break;
            
            
        default:
            break;
    }
    
    [self lengthLimitBlock:textField];
}


//- (NSString *)getLimitString:(UITextField *)field{
//
//    if (field.text.length == 0) {
//        return @"";
//    }else if (field.text.length == 1 && [field.text isEqualToString:@""]){
//        return @"";
//    }else if (field.text.length == 1 && ![field.text isEqualToString:@""]){
//        return field.text;
//    }else{
//        return [field.text substringToIndex:field.text.length -1];
//    }
//    return @"";
//}

/**
 获取TextField输入范围
 @param textField textField
 @return 范围
 */
- (NSRange)getTextFieldRange:(UITextField *)textField
{
    NSInteger adaptedLength = textField.maxLength > 0 ? MIN(textField.text.length, textField.maxLength) : MIN(textField.text.length, MAXFLOAT);
    NSRange range = NSMakeRange(0, adaptedLength);
    
    return range;
}


/**
 输入类型验证
 
 @param aStr 输入字符串
 @param format 验证格式
 @return BOOL
 */
- (BOOL)inputTypeVerification:(NSString *)aStr format:(NSString *)format{
    NSCharacterSet* filterCS = [[NSCharacterSet characterSetWithCharactersInString:format] invertedSet];
    NSString *filterString = [[aStr componentsSeparatedByCharactersInSet:filterCS] componentsJoinedByString:@""];
    
    return [aStr isEqualToString:filterString];
}


/**
 无限制（可以输入任何类型）
 @param textField textField
 */
- (void)textFieldStringTypeNone:(UITextField *)textField
{
//    textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
    //    if (textField.text.length > self.maxLength) {
    //        textField.text =  [textField.text substringToIndex:textField.text.length -1];
    //    }
}

/**
 只能输入数字
 @param textField textField
 */
- (void)textFieldStringTypeNumber:(UITextField *)textField
{
    BOOL flag = [self inputTypeVerification:textField.text format:kDNUMBERS];
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        if ([DCSpeedy isBlankString:textField.text]) {
            textField.text = @"";
        } else {
            //如果不是空，取现有的信息长度-1的内容
//            textField.text = [textField.text substringToIndex:textField.text.length -1];
            textField.text = @"";
        }
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}

/**
 只能输入字母
 @param textField textField
 */
- (void)textFieldStringTypeLetter:(UITextField *)textField
{
    BOOL flag = [self inputTypeVerification:textField.text format:kDLETTER];;
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        textField.text = [textField.text substringToIndex:textField.text.length -1];
        
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}

//CJTextFieldStringTypeMoneyValue

///  金额验证
/// @param textField <#textField description#>
- (void)textFieldStringTypeMoneyValue:(UITextField *)textField
{
    BOOL flag = [CYCheckRegular cy_checkFloatMoney: textField.text];
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        //        textField.text = [textField.text substringToIndex:textField.text.length -1];
        
        if (textField.text.length <= 1) {
            textField.text = @"";
        }else{
            textField.text = [textField.text substringToIndex:textField.text.length -1];
            
        }
        
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}

///  小数点后三位验证
- (void)textFieldStringTypeThreeDecimalPlaces:(UITextField *)textField
{
    BOOL flag = [CYCheckRegular cy_checkThreeDecimalPlaces: textField.text];
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        NSLog(@"%@", textField.text);
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        
        if (textField.text.length <= 1) {
            textField.text = @"";
        }else{
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
            
        }
        
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}


/// 密码验证
- (void)textFieldStringTypePassword:(UITextField *)textField
{
    BOOL flag = [CYCheckRegular cy_checkTeshuZifuNumber: textField.text];
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    } else {
        
        if ([DCSpeedy isBlankString:textField.text] == NO) {
//            textField.text = [textField.text substringToIndex:textField.text.length -1];
            textField.text = @"";
        } else {
            textField.text = @"";
        }
        
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}



///// 验证银行卡
///// @param textField <#textField description#>
//- (void)textFieldStringTypeBanckNum:(UITextField *)textField
//{
////    BOOL flag = [self inputTypeVerification:textField.text format:kDLETTER];
//
//    if ([CJRegular getIsBankCardNum:textField.text]){
////        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
//        if (self.isTextFieldTypeBlock) {
//            self.isTextFieldTypeBlock(YES);
//        }
//    }
//    else{
//
//        textField.text = [self getLimitString:textField];
//        if (self.isTextFieldTypeBlock) {
//            self.isTextFieldTypeBlock(NO);
//        }
//    }
//}



@end
